package database

import (
	"context"
	"log"
	"ourplansystem/server/ent"
	"ourplansystem/server/ent/user"
	"time"

	"golang.org/x/crypto/bcrypt"
)

// SeedData 初始化种子数据
func SeedData(ctx context.Context, client *ent.Client) error {
	// 检查是否已经有用户数据
	userCount, err := client.User.Query().Count(ctx)
	if err != nil {
		return err
	}

	// 如果已经有用户数据，跳过初始化
	if userCount > 0 {
		log.Println("用户数据已存在，跳过用户初始化")
	} else {
		// 创建初始用户
		users := []struct {
			username    string
			password    string
			displayName string
		}{
			{
				username:    "user1",
				password:    "lxy520",
				displayName: "超级无敌宇宙第一帅哥",
			},
			{
				username:    "user2",
				password:    "dxb1314",
				displayName: "超级无敌宇宙第一美女",
			},
		}

		for _, u := range users {
			// 密码加密
			hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.password), bcrypt.DefaultCost)
			if err != nil {
				return err
			}

			// 创建用户
			_, err = client.User.Create().
				SetUsername(u.username).
				SetPassword(string(hashedPassword)).
				SetDisplayName(u.displayName).
				Save(ctx)

			if err != nil {
				return err
			}

			log.Printf("创建用户成功: %s (%s)", u.displayName, u.username)
		}
	}

	// 创建恋爱统计数据
	statCount, err := client.RelationshipStat.Query().Count(ctx)
	if err != nil {
		return err
	}

	if statCount > 0 {
		log.Println("恋爱统计数据已存在，跳过初始化")
	} else {
		togetherSince, _ := time.Parse("2006-01-02", "2025-10-07")
		_, err = client.RelationshipStat.Create().
			SetTogetherSince(togetherSince).
			SetMeetCount(0).
			Save(ctx)
		if err != nil {
			return err
		}
		log.Println("创建恋爱统计数据成功: 在一起日期 2025-10-07")
	}

	log.Println("初始数据创建完成")
	return nil
}

// GetUserByUsername 根据用户名查询用户
func GetUserByUsername(ctx context.Context, client *ent.Client, username string) (*ent.User, error) {
	return client.User.Query().
		Where(user.UsernameEQ(username)).
		Only(ctx)
}

// VerifyPassword 验证密码
func VerifyPassword(hashedPassword, password string) error {
	return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
}
